const eventEmiter = require('wy-EventEmiter');
const config = require('wy-Config');
const pomelo = require('wy-Pomelo');
//微信模块的功能调用
let isRecordding = false;
let autoStopTimer = null;
let recordFiles = [];  //所有需要播放的录音都先来这里存着，然后一个个播放
let isPlayRecord = false; //是否正在播放录音

let _playOneRecord = function () {
    if (recordFiles.length === 0) {
        isPlayRecord = false;
    } else {
        let wxAudio = wx.createInnerAudioContext();
        let recordFile = recordFiles.shift();
        wxAudio.src = config.readRecordRootUrl + recordFile.fileName;
        wxAudio.loop = false;
        wxAudio.onPlay(() => {
            cc.audioEngine.pauseAll();
            eventEmiter.emit('playRecordStart', recordFile);
        });
        wxAudio.onEnded(() => {
            if (recordFiles.length == 0) {
                cc.audioEngine.resumeAll();
            }
            eventEmiter.emit('playRecordEnd', recordFile);
            wxAudio.destroy();
            _playOneRecord();
        })
        wxAudio.play();
    }
}

let _playAllRecord = function () {
    if (isPlayRecord) {
        return;
    }
    if (recordFiles.length > 0) {
        isPlayRecord = true;
        _playOneRecord();
    }
}

let WeChat = {

    init(){
        var obj = typeof(window.wx);
        if(obj != 'undefined'){
            var option = wx.getLaunchOptionsSync();
            this.wxLaunchQuery = option.query;
            
            var self = this;
            wx.onShow(function (option){
                !self.wxLaunchQuery && (self.wxLaunchQuery = option.query);
            })

            wx.onShareAppMessage(function () {
                return {
                    title: '挑战荒岛',
                    query:'openid='+(global.Data.openid?global.Data.openid:0),
                    imageUrl: wxDownloader.REMOTE_ROOT + 'wechatshare.png'
                }
            })
            wx.showShareMenu()
        } else {
            this.wxLaunchQuery = '';
        }
    },

    getLaunchOption(){
        return this.wxLaunchQuery;
    },

    clearOption(){
        this.wxLaunchQuery = null;
    },

    cleanResource(){
        var fileutil = require('WxFileUtils');

        if(this.btnLogin){
            this.btnLogin.destroy();
            this.btnLogin = null
        }
        cc.sys.localStorage.clear();
        delete window.global;
        wx.clearStorage();
        wx.showToast({title:'正在清理，稍后会自动重启'})

        
        cc.find('Canvas').removeAllChildren();
        cc.loader.releaseAll();
        fileutil.removeFiles[[wx.env.USER_DATA_PATH+'/config.json'],function(){
            console.log('删除配置文件成功')
        }]

        fileutil.clearFile(wx.env.USER_DATA_PATH+'/res/raw-assets',function(pro){
            console.log('删除进度:',pro)
        },function(){
            console.log('删除完成')
            cc.sys.localStorage.clear();
            // global.UI.ToolTip({message:'正在清理，稍后会自动重启'})
            cc.game.restart();
        })
    },
    
    //微信自动登录
    login: function (cb) {
        let self = this;

        function getLocation(data){
            self.getLocation(function (location) {
                data.latitude = location.latitude,
                data.longitude = location.longitude,
                cb(data);
            })
        }
        function showBtn(){
            wx.login({
                success: function (res) {
                    var systemInfo = wx.getSystemInfoSync();
                    var width = 192;
                    var height = 73
                    var left = systemInfo.screenWidth / 2 - width / 2;
                    var top = .8 * systemInfo.screenHeight - height / 2;
                    self.btnLogin = wx.createUserInfoButton({
                        type: "image",
                        image: wxDownloader.REMOTE_ROOT+"btn_weixin.png",
                        style: {
                        left: left,
                        top: top,
                        width: width,
                        height: height
                        },
                        withCredentials: true
                    });
                    self.btnLogin.onTap(function (data) {
                        wx.setStorageSync('wecode',res.code);
                        self.getLocation(function (location) {
                            let obj = {
                                code: res.code,
                                userinfo : data['userInfo'],
                                encryptedData: data.encryptedData,
                                iv: data.iv,
                                signature: data.signature,
                                latitude: location.latitude,
                                longitude: location.longitude,
                            };
                            wx.setStorageSync('weloginfo',JSON.stringify(obj));
                            cb(obj);
                            self.btnLogin.destroy();
                            self.btnLogin = null;
                        })
                    });
                    self.btnLogin.show();
                }
            })
        }

        var code = wx.getStorageSync('wecode');
        if(!!code){
            wx.checkSession({
                success:()=>{
                    var info = wx.getStorageSync('weloginfo');
                    var obj = JSON.parse(info);
                    delete obj.code;
                    getLocation(obj);
                },
                fail:()=>{
                    showBtn();
                }
            })
        } else {
            showBtn();
        }
        
    },
    //获取地理位置  回掉函数中的res.latitude,res.longitude为经纬度
    getLocation: function (cb) {
        if(CC_WECHATGAME){
            wx.getLocation({
                success: function (res) {
                    cb(res);
                },
                fail:function(){
                    cb({latitude:999,longitude:999});
                }
            });
        } else {
            setTimeout(function(){
                cb({latitude:100,longitude:100})
            }, 10);
        }
    },
    //转发
    //开始录音
    startRecord: function (roomNo) {
        if (isRecordding) { return; }
        cc.log('开始录音');
        isRecordding = true;
        isPlayRecord = true;
        cc.audioEngine.pauseAll();
        //开启自动关闭录音定时器
        autoStopTimer = setTimeout(() => {
            WeChat.stopRecord();
        }, 10000);
        let RecorderManager = wx.getRecorderManager();
        RecorderManager.start({
            sampleRate: 12000,
            numberOfChannels: 1,
            encodeBitRate: 24000,
            format: 'mp3',
            frameSize: 10
        });
        RecorderManager.onStop(function (data) {
            cc.log('录音结束');
            isRecordding = false;
            isPlayRecord = false;
            _playAllRecord(f);
            cc.audioEngine.resumeAll();
            eventEmiter.emit('stopRecord');
            let tempFilePath = data.tempFilePath;
            //let fileSize=data.fileSize;
            //let duration=data.duration;
            let fileName = `${roomNo}_${new Date().getTime()}`;
            cc.log('开始上传录音', tempFilePath);
            wx.uploadFile({
                url: config.uploadRecordUrl,
                filePath: tempFilePath,
                name: fileName,
                formData: {
                    fileName: fileName + '.mp3'
                },
                success: function (res) {
                    cc.log('MP3文件上传成功', res);
                    //eventEmiter.emit('stopRecord',fileName);
                    pomelo.request('room.manager.broadcastRecord', { roomNo: roomNo, fileName: fileName + '.mp3' }, (data) => { });
                }
            });
        });
        eventEmiter.emit('startRecord');
    },
    //停止录音
    stopRecord: function () {
        if (!!autoStopTimer) {
            clearTimeout(autoStopTimer);
            autoStopTimer = null;
        }
        let RecorderManager = wx.getRecorderManager();
        RecorderManager.stop();
    },
    //播放网络录音
    playRecord: function (_id, fileName) {
        recordFiles.push({ _id: _id, fileName: fileName });
        _playAllRecord();
    },
    //分享
    share: function (title, queryObj, successCallBack, imageUrl = 'https://xlsocket.073c.com/image/share.png') {
        let query = Object.keys(queryObj).map(function (key) {
            return key + '=' + queryObj[key];
        }).join("&");
        console.log(arguments)
        wx.shareAppMessage({
            title: title,
            imageUrl: imageUrl,
            query: query,
            success: successCallBack
        })
    },
    //游戏退出
    exit: function () {
        wx.exitMiniProgram({});
    },
    //游戏截图
    screenshot: function (argObj, cb) {
        var canvas = cc.game.canvas;
        var width = cc.winSize.width;
        var height = cc.winSize.height;
        let obj = {
            x: 0,
            y: 0,
            width: width,
            height: height,
            destWidth: width,
            destHeight: height,
            success(res) {
                cb(res.tempFilePath);
            }
        };
        Object.assign(obj, argObj);
        canvas.toTempFilePath(obj);
    },
    cleanOldAssets:function(cb){
        var wfu = require('WxFileUtils');
        wfu.init();
        console.log('cleanOldAssets path:',wx.env.USER_DATA_PATH)
  
        var isLogin = false;
        var mainFile = wx.env.USER_DATA_PATH + '/res'
        var isExe = false;
        var remove = function(){
          wfu.removeAllDir(wx.env.USER_DATA_PATH + '/res', function (i) {
            console.log('删除config文件夹成功:' + i)
            isExe = true;
            if(isLogin){
                return;
            }
            wfu.removeDir(mainFile, function (p, t) {
              console.log('检测resources:', t);
              if (t && !isLogin) {
                cb();
                isLogin = true;
              }
            })
          }, 0)
        }
        setTimeout(remove,1000)
  
        setTimeout(function(){
          if (!isExe){
            cb();
            isLogin = true;
          }
        },10000)
      }
};

WeChat.init();

module.exports = WeChat;